import {BasePage, BasePageData} from "../common/core/BasePage";
import {DataLoader, field} from "../../modules/coreModule/data/DataLoader";
import {Banner, bannerRepo} from "../../modules/miscModule/data/Banner";
import {TaskIndexData, TaskStatus, TaskType} from "../../modules/taskModule/data/Task";
import {page, pageFunc} from "../common/PageBuilder";
import {UserPage} from "../common/partPages/UserPage";
import {QueryPage} from "../common/partPages/QueryPage";
import {userMgr, waitForLogin} from "../../modules/userModule/managers/UserManager";
import {waitForDataLoad} from "../../modules/coreModule/managers/DataManager";
import {TaskInterface} from "../../modules/taskModule/TaskCommon";
import {alertMgr} from "../../modules/coreModule/managers/AlertManager";
import {blockLoading, showLoading} from "../../modules/coreModule/managers/LoadingManager";
import {CoreLoading} from "../../modules/coreModule/CoreCommon";
import {PickerPage} from "../common/partPages/PickerPage";
import {pageMgr} from "../../modules/coreModule/managers/PageManager";
import {BannerDetailPage} from "../bannerDetail/BannerDetailPage";

enum Order {Rand = 0, Desc = -1, Asc = 1}

class Data extends BasePageData {

	@field([Banner])
	banners: Banner[] = []
	@field([TaskIndexData])
	tasks: TaskIndexData[] = [];
	@field
	typeIdx: number = 0;
	@field
	type: string = "全部";

	@field(Order)
	salaryOrder: Order = Order.Rand;

	@field(Order)
	timeOrder: Order = Order.Rand;
}

const TitleArr = ["场地", "日常兼职", "军事训练"];

// const FilterStatuses = [TaskStatus.Normal]
const SelectTypeTitle = "选择任务类型"

@page("recruit", "招募大厅")
export class RecruitPage extends BasePage<Data> {

	data = new Data();

	/**
	 * 部分页
	 */
	public pickerPage: PickerPage = new PickerPage();
	public userPage = new UserPage();
	public queryPage: QueryPage = new QueryPage(
		this.loadTasks.bind(this), {
			type: ["_.neq", TaskType.Military],
			status: TaskStatus.Normal
		});

	async onLoad(e) {
		super.onLoad(e);
		await this.loadData();
	}

	@showLoading(CoreLoading.Mask)
	@blockLoading
	@waitForLogin
	@waitForDataLoad
	private async loadData() {
		this.queryPage.refresh();
		await this.setData({
			banners: bannerRepo().find(),
			typeIdx: 0
			// tasks: await this.loadTasks({offset: 0, count: 20})
		})
	}

	/**
	 * 根据当前排序状态提供offset和count获得task
	 * @param queryParams
	 */
	@pageFunc
	@showLoading(CoreLoading.Mask)
	@blockLoading
	private async loadTasks(queryParams) {
		const province = userMgr().location.province
			?.replace("省", "")
			?.replace("市", "")
		const extraParams = {
			sortSalary: this.data.salaryOrder,
			sortTime: this.data.timeOrder,
			province //, excludeFull: true
		};
		let newTasks: TaskIndexData[] = (await TaskInterface.GetTasks(
			{...queryParams, ...extraParams}
		)).tasks.map(t =>
			DataLoader.load(TaskIndexData, t)
		)
		newTasks = newTasks.filter(t => t.particCount < t.count);

		await this.setData({
			tasks: this.data.tasks.concat(newTasks)
		})
	}

	/**
	 * 获取类型数组
	 */
	public typeTexts() {
		const res = TitleArr.map(t => ({name: t}));
		res.unshift({name: "全部"});
		return res;
		// const res: {name: string}[] = this.data.tasks.map(r => ({name: r.tags[0]}));
		// // 消除重复
		// let types: {name: string}[] = [];
		// for(let i=0; i < res.length; ++i) {
		// 	let y;
		// 	for (y = 0; y < types.length; ++y) {
		// 		if(types[y].name == res[i].name) break;
		// 	}
		// 	if (y == types.length) types.push({name: res[i].name});
		// }
		// types.push({name: "全部"});
		// return types;
	}

	/**
	 * 类型点击回调
	 */
	@pageFunc
	public async onTypeTap(){
		const texts = this.typeTexts();
		const typeIdxs = (await this.pickerPage.startPicker(
			SelectTypeTitle, texts, this.data.typeIdx));
		if (typeIdxs == null) return;

		await this.setData({
			typeIdx: typeIdxs[0],
			type: texts[typeIdxs[0]].name
		});
		if (typeIdxs[0] == 0) // 全部
			this.queryPage.setFilter();
		else
			this.queryPage.setFilter({type: typeIdxs[0]});
		this.queryPage.resetPage();
		this.data.tasks = [];
		await this.queryPage.refresh();
	}

	@pageFunc
	public async sortByPrice() {
		await this.setData({
			salaryOrder: this.data.salaryOrder ?
				-this.data.salaryOrder : Order.Asc,
			timeOrder: Order.Rand,
			tasks: []
		})
		this.queryPage.refresh();
	}

	@pageFunc
	public async sortByTime() {
		await this.setData({
			timeOrder: this.data.timeOrder ?
				-this.data.timeOrder : Order.Asc,
			salaryOrder: Order.Rand,
			tasks: []
		})
		this.queryPage.refresh();
	}

	@pageFunc
	public hintForFee() {
		alertMgr().showAlert(
			"本平台将收取您项目报酬的5%作为手续费"
		)
	}

	@pageFunc
	public toBannerDetail(e) {
		let bannerId = e.currentTarget.dataset.banner._id;
		// @ts-ignore
		pageMgr().push(BannerDetailPage, {bannerId}).then();
	}

}
